package com.defysoft.waukids.diary;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.Data_Type.WK_DIARY_PHOTO;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Diary_Detail_Edit extends BaseActivity implements OnClickListener {
	Toolbar toolbar;
	EditText et[] = new EditText[2];
	ImageView iv_img[] = new ImageView[10];
	View stamp[] = new View[3];
	FrameLayout fl[] = new FrameLayout[10];
	View btn_save;
	LinearLayout ly,ly_1;
	String PK_Dia_Code = "";
	Custom_Data_Type.DiaryDetailLoad DiaryDetailLoad;
	ArrayList<WK_DIARY_PHOTO> photoList;
	private ImageLoader imageLoader;
	DisplayImageOptions defaultOptions;
	String stamp_code = "";
	Bitmap bitmap;
	BitmapFactory.Options options;
	Sqlite_Connect sqlite_Connect;
	PublicSharedpreferences psf;
	public Data_Sharedpreferences.SF_Member member;
	int photo_count;
	private final int SUCCESS = 10;
	private final int FAIL = 9;
	private final int NETWORK_ERR = 8;
	private final int EDIT_SUCCESS = 7;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.diary_detail_edit);
		setStartData();
		setStartToolbar();
		startNetwork(0);
		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}

	private void setStartToolbar() {
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	public void setStartData() {
		super.setStartData();
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		sqlite_Connect = new Sqlite_Connect(this);
		PK_Dia_Code = getIntent().getStringExtra("PK_Dia_Code");	
		stamp[0] = (View) findViewById(R.id.DIARY_EDIT_STAMP_1);
		stamp[1] = (View) findViewById(R.id.DIARY_EDIT_STAMP_2);
		stamp[2] = (View) findViewById(R.id.DIARY_EDIT_STAMP_3);
		et[0] = (EditText) findViewById(R.id.DIARY_EDIT_TITLE);
		et[1] = (EditText) findViewById(R.id.DIARY_EDIT_SUB);
		toolbar = (Toolbar) findViewById(R.id.DIARY_MAIN_EDIT_TOOLBAR);
		btn_save = (View) findViewById(R.id.DIARY_EDIT_TOOLBAR_SAVE);
		for (int i = 0; i < stamp.length; i++) {
			stamp[i].setOnClickListener(this);
		}
		btn_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog();
			}
		});
		ImageLayout();
		Init();
	}

	void mainThread() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_DIARY_DETAIL_LOAD + "&PK_Dia_Code="
							+ PK_Dia_Code));
			if (jsonObject.getBoolean("success")) {
				DiaryDetailLoad = JsonParser.diaryDetailLoad(jsonObject
						.getString("payload"));
				photoList = JsonParser.diaryPhotoList(jsonObject
						.getString("photo"));
				photo_count = jsonObject.getInt("count");
				onNetworkCallback(SUCCESS, "");
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR,  e.toString()+" where mainThread() ");
		}
	}

	void editThread() {
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_DIARY_DETAIL_EDIT + "&PK_Dia_Code="
							+ PK_Dia_Code + "&subject="
							+ et[1].getText().toString() + "&title="
							+ et[0].getText().toString() + "&stamp="
							+ stamp_code));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(EDIT_SUCCESS, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(NETWORK_ERR, e.toString()+" where editThread()");
		}
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {

			@Override
			public void run() {
				switch (cho) {
				case 0:
					mainThread();
					break;

				case 1:
					editThread();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			stamp_code = DiaryDetailLoad.Dia_Stamp;
			if (stamp_code.equals("0")) {

			} else {
				if (stamp_code.equals("1")) {
					this.stamp[0].setBackgroundResource(R.drawable.stamp_one_fill);
				} else if (stamp_code.equals("2")) {
					this.stamp[1].setBackgroundResource(R.drawable.stamp_two_fill);
				} else if (stamp_code.equals("3")) {
					this.stamp[2].setBackgroundResource(R.drawable.stamp_three_fill);
				}
			}
			et[0].setText(DiaryDetailLoad.Dia_Name);
			et[1].setText(DiaryDetailLoad.Dia_Sub);

			imageSetting();
			break;
		case EDIT_SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			setResult(REFRESH_CODE);
			finish();
			break;

		case FAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;

		case NETWORK_ERR:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Diary_Detail_Edit", member.Email);
			break;
		}
	}

	void ImageLayout() {
		// 이미지 감싸고있는 뷰
		ly = (LinearLayout) findViewById(R.id.DIARY_EDIT_PHOTO_CONTAINER);
		ly_1 = (LinearLayout)findViewById(R.id.DIARY_EDIT_PHOTO_CON_1);
		fl[0] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_1);
		fl[1] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_2);
		fl[2] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_3);
		fl[3] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_4);
		fl[4] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_5);
		fl[5] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_6);
		fl[6] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_7);
		fl[7] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_8);
		fl[8] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_9);
		fl[9] = (FrameLayout) findViewById(R.id.DIARY_EDIT_PHOTO_FRAME_10);
		// 사진 들어갈 이미지 뷰
		iv_img[0] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_1);
		iv_img[1] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_2);
		iv_img[2] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_3);
		iv_img[3] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_4);
		iv_img[4] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_5);
		iv_img[5] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_6);
		iv_img[6] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_7);
		iv_img[7] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_8);
		iv_img[8] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_9);
		iv_img[9] = (ImageView) findViewById(R.id.DIARY_EDIT_PHOTO_10);
	}

	void imageSetting() {
		if (photo_count == 0) {

		} else {
			ly.setVisibility(View.VISIBLE);
			ly_1.setOnClickListener(this);
			for (int i = 0; i < photo_count; i++) {
				fl[i].setVisibility(View.VISIBLE);
				imageLoader.displayImage(PublicConstant.HTTP_URL_DIARYPHOTO
						+ photoList.get(i).Dia_Pho_IMG, iv_img[i],
						defaultOptions);
			}
		}
	}

	// 이미지 로더 옵션
		void Init() {
			defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true)
					.cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY)
					.considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
					.build();

			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					this).threadPriority(Thread.NORM_PRIORITY - 2)
					.denyCacheImageMultipleSizesInMemory()
					.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
					.memoryCacheSize(2 * 1024 * 1024).memoryCacheSizePercentage(20)
					.diskCacheSize(50 * 1024 * 1024).diskCacheFileCount(100)
					.diskCacheExtraOptions(480, 320, null)
					.diskCacheFileNameGenerator(new Md5FileNameGenerator())
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.writeDebugLogs() // Remove for release app
					.build();
			imageLoader = ImageLoader.getInstance();
			imageLoader.init(config);
		}

	// 네.아니오.선택다이얼로그
	void alertDialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog alert;
		builder.setMessage("수정된 내용을 저장하시겠습니까?")
				.setCancelable(false)
				.setPositiveButton("네", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						startNetwork(1);
					}
				})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		alert = builder.create();
		alert.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.DIARY_EDIT_STAMP_1:
			if(stamp_code.equals("1")){
				stamp_code ="0";
				this.stamp[0].setBackgroundResource(R.drawable.stamp_one);
			}else{
			stamp_code="1";
			stamp_change(stamp_code);
			}
			break;
		case R.id.DIARY_EDIT_STAMP_2:
			if(stamp_code.equals("2")){
				stamp_code ="0";
				this.stamp[1].setBackgroundResource(R.drawable.stamp_one);
			}else{
			stamp_code="2";
			stamp_change(stamp_code);
			}
			break;
		case R.id.DIARY_EDIT_STAMP_3:
			if(stamp_code.equals("3")){
				stamp_code ="0";
				this.stamp[2].setBackgroundResource(R.drawable.stamp_one);
			}else{
			stamp_code="3";
			stamp_change(stamp_code);
			}
			break;
		case R.id.DIARY_EDIT_PHOTO_CON_1:
			Toast.makeText(Diary_Detail_Edit.this, "사진은 수정 및 삭제를 할수 없습니다.",
					Toast.LENGTH_SHORT).show();
			break;
		}
	}
	
	void stamp_change(String stamp_code){
		if(stamp_code.equals("0")){
			stamp[0].setBackgroundResource(R.drawable.stamp_one);
			stamp[1].setBackgroundResource(R.drawable.stamp_two);
			stamp[2].setBackgroundResource(R.drawable.stamp_three);	
		}
		if(stamp_code.equals("1")){
			stamp[0].setBackgroundResource(R.drawable.stamp_one_fill);
			stamp[1].setBackgroundResource(R.drawable.stamp_two);
			stamp[2].setBackgroundResource(R.drawable.stamp_three);	
		}
		if(stamp_code.equals("2")){
			stamp[0].setBackgroundResource(R.drawable.stamp_one);
			stamp[1].setBackgroundResource(R.drawable.stamp_two_fill);
			stamp[2].setBackgroundResource(R.drawable.stamp_three);	
		}
		if(stamp_code.equals("3")){
			stamp[0].setBackgroundResource(R.drawable.stamp_one);
			stamp[1].setBackgroundResource(R.drawable.stamp_two);
			stamp[2].setBackgroundResource(R.drawable.stamp_three_fill);	
		}
		
	}
	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.toast_layout, null);
			TextView toast_tv = (TextView)layout.findViewById(R.id.TOAST_LAYOUT_TV);
			Toast toast = new Toast(Diary_Detail_Edit.this);
			toast.setView(layout);
			toast_tv.setText(intent.getStringExtra("PUSH_NAME")+" : "+intent.getStringExtra("PUSH_SUB"));
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
		}
	};
}
